<?php
/*
	Copyright (c) 2010 Lexalytics Inc.

	Permission is hereby granted, free of charge, to any person
	obtaining a copy of this software and associated documentation
	files (the "Software"), to deal in the Software without
	restriction, including without limitation the rights to use,
	copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following
	conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
	OTHER DEALINGS IN THE SOFTWARE.

*/
	
	class zephyrEntity
	{
		public $form;
		public $normalized;
		public $label;
		
		
		function __construct($form,$normalized)
		{
			$this->form = $form;
			$this->normalized = $normalized;
			$this->label = "Custom Entity";
		}
	}
	
	class zephyrTag
	{
		public $tag;
		public $query;

		function __construct($tag,$query)
		{
			$this->tag = $tag;
			$this->query = $query;
		}
	}
	
	class zephyrClient
	{
		protected $publickey;
		protected $privatekey;
		protected $server;
		protected $curl;

		function __construct($publickey,$privatekey)
		{
			$this->publickey = $publickey;
			$this->privatekey = $privatekey;
			$this->server = "http://zephyr.lexalytics.com";
			$this->curl = curl_init();
		}

		//List all the projects associated with the public key.
		//It returns an associative array with the project label and
		//volume of content associated with it.
		function listProjects()
		{
			$ret = array();
			$params = array();
			$results = $this->processRequest($params,"list/projects");
			
			foreach($results->results as $result)
			{
				$temp = array();
				$temp['label'] = $result->label;
				$temp['volume'] = $result->volume;
				$ret[] = $temp;
			}
			return $ret;
		}

		function getProjectData($project,$date="",$time="",$maxresults="")
		{
			$ret = array();
			$params = array();
			
			$params['publickey'] = $this->publickey;
			$params['output'] = "json";
			$params['project'] = $project;
			
			
			$params['project'] = $project;
			if ($date != "")
			{
				$params['date'] = $date;
			}

			if ($time != "")
			{
				$params['time'] = $time;
			}
			
			if ($maxresults != "")
			{
				$params['maxresults'] = $maxresults;
			}

			$results = $this->processRequest($params,"results/assets");
			$ret['last_date'] = $results->last_date;
			foreach($results->results as $asset)
			{
				$temp = array();
				
				$temp['sentiment'] = $asset->sentiment;
				$temp['dateadded'] = $asset->dateadded;
				$temp['url'] = $asset->location;
				$temp['title'] = $asset->location;

				$temp['entities'] = array();
				foreach($asset->{0} as $objentity)
				{
					$entity['label'] = $objentity->entity;
					$entity['type'] = $objentity->type;
					$entity['sentiment'] = $objentity->magnitude;
					$entity['mentions'] = $objentity->mentions;
					$temp['entities'][] = $entity;
				}

				$temp['themes'] = array();
				foreach($asset->{1} as $objtheme)
				{
					$theme['theme'] = $objtheme->theme;
					$theme['sentiment'] = $objtheme->magnitude;
					$temp['themes'][] = $theme;
				}

				$temp['summary'] = "";
				foreach($asset->{2} as $objmetadata)
				{
					if ($objmetadata->label == "lxa_summary")
					{
						$temp['summary'] = $objmetadata->value;
					}
					else if ($objmetadata->label == "lxa_title")
					{
						$temp['title'] = $objmetadata->value;
					}
					else
					{
						$temp[$objmetadata->label] = $objmetadata->value;
					}
				}
				$ret['assets'][] = $temp;
			}
			return $ret;
		}


		
		//The next four functions are used for adding the various search generating feeds
		function addGoogleSearch($project,$search,$id)
		{
			$params = array();
			$params['project'] = $project;
			$params['newsid'] = $id . "_news";
			$params['blogid'] = $id . "_blog";
			$params['query'] = $search;
			$params['schedule'] = "3600";
			$results = $this->processRequest($params,"add/googlequery");
		}

		function addTwitterSearch($project,$search,$id)
		{
			$params = array();
			$params['project'] = $project;
			$params['id'] = $id;
			$params['query'] = $search;
			$params['schedule'] = "600";
			$results = $this->processRequest($params,"add/twitterquery");
		}
		
		
		function addWordPressSearch($project,$search,$id)
		{
			$params = array();
			$params['project'] = $project;
			$params['id'] = $id;
			$params['query'] = $search;
			$params['schedule'] = "3600";
			$results = $this->processRequest($params,"add/wordpressquery");
		}
		
		function addBlogpulseSearch($project,$search,$id)
		{
			$params = array();
			$params['project'] = $project;
			$params['id'] = $id;
			$params['query'] = $search;
			$params['schedule'] = "3600";
			$results = $this->processRequest($params,"add/blogpulsequery");
		}

		//These functions enable you to modify the way that data in Tempest will be processed
		
		//$entities is an array of zephyrEntity objects;
		function addCustomEntities($project,$entities)
		{
			$params = array();
			$params['project'] = $project;
			$entitylist = "";
			foreach($entities as $entity)
			{
				$entitylist .= $entity->form ."\t".$entity->normalized."\t" . $entity->label ."\n";
			}
			
			$params['list'] = $entitylist;
			$results = $this->processRequest($params,"add/entitylist");
		}

		function addTags($project,$tags)
		{
			$params = array();
			$params['project'] = $project;
			$taglist = "";
			foreach($tags as $tag)
			{
				$taglist .= $tag->tag ."\t".$tag->query."\n";
			}
			$params['list'] = $taglist;
			$results = $this->processRequest($params,"add/taglist");
		}

		//Add a feed and some feed metadata
		function addFeed($project,$id,$url)
		{
			$params = array();
			$params['project'] = $project;
			$params['id'] = $id;
			$params['url'] = $url;
			$results = $this->processRequest($params,"add/feed");
		}


		function addFeedMetadata($project,$id,$label,$value)
		{
			$params = array();
			$params['project'] = $project;
			$params['id'] = $id;
			$params['label'] = $label;
			$params['value'] = $value;
			$results = $this->processRequest($params,"add/feedmetadata");

		}
		
		//Add a piece of content from a URL
		function addUrl($project,$id,$url)
		{
			$params = array();
			$params['project'] = $project;
			$params['id'] = $id;
			$params['url'] = $url;
			$results = $this->processRequest($params,"add/url");
		}

		//Add a loadfile
		function addLoadFile($project,$loadfile)
		{
			$params = array();
			$params['project'] = $project;
			$params['loadfile'] = "@".$loadfile;
			$results = $this->processRequest($params,"add/loadfile");
		}
		

		protected function processRequest($params,$url)
		{
			//Set the output type
			$params['output'] = "json";
			
			//Generate the encoded key
			$params['publickey'] = $this->publickey;
			$params['encodedkey'] = $this->generateEncodedKey($params);

			curl_setopt($this->curl, CURLOPT_URL, $this->server ."/". $url . ".php");
			curl_setopt($this->curl, CURLOPT_POST, 1);
			curl_setopt($this->curl, CURLOPT_POSTFIELDS, $params);
			curl_setopt($this->curl, CURLOPT_RETURNTRANSFER,1);

			$contents = curl_exec($this->curl);
			echo($contents);
			$decoded = json_decode($contents);
			
			//Check for an error condition
			
			return $decoded;
		}

		protected function generateEncodedKey($params)
		{
	        $ret = "";
	        foreach($params as $key => $value)
	        {
	            if ($key != "encodedkey")
		        {
	                $ret .= $key . "=" . rawurlencode($value);
	            }
			}

			$ret = md5($this->publickey.$this->privatekey.$ret);
			return $ret;
		}
		
		function deleteProject($project)
		{
			$ret = array();
			$params = array();
			$params['project'] = $project;
			$results = $this->processRequest($params,"delete/project");
		}
		
		function deleteAllProjects()
		{				
			$projects = $this->listProjects();
			
			//Then for each of the projects, get the data 
			foreach($projects as $project)
			{
					$ret = array();
					$params = array();
					$params['project'] = $project['label'];
					$this->processRequest($params,"delete/project");	
			}		
		}
	}

?>